import React, { Component } from 'react';
import WPT from 'wpt';
import NumInputView from 'modules/InputNum/NumInputView';
import InputNum from 'modules/InputNum/index';
import sliderCheck from 'modules/sliderCheck';
import { throttle } from 'modules/RX';
import { loginReport } from 'modules/ReportAjax';
import cx from 'classnames';
import CountryCodeList from 'modules/verifyTelephoneModal/countryCodeList/CountryCodeList';
import Util from '../../util';
import S from './index.m.less';

const API = {
    sendCode: `${WPT.API_HOST}app/v1.0/user/send-login-code`, // 发送验证码接口
    login: `${WPT.API_HOST}app/v1.0/user/login`, // 登录接口
};

class WptWapLogin extends Component {
    static defaultProps = {
        // 成功回调
        scb: () => {},
        // 失败回调
        fcb: () => {},
        // 用户关闭窗口回调
        ccb: () => {},
    };

    constructor(props) {
        super(props);
        this.state = {
            // 输入框是否获得焦点
            inputOnFocus: false,
            // 电话号码
            telephone: '',
            // 国家缩写
            country: 'CN',
            // 国际区号
            countryCode: '86',
            // 手机号正则规则
            pattern: '^(86){0,1}1\\d{10}$',
            // 验证码重发倒计时 60s
            seconds: '60',
            // 展示区号选择界面
            showCountryCode: false,
            // 展示验证码输入界面
            showCodeInputPage: false,
            // 验证码
            code: ['', '', '', ''],
            // 验证码第几位获得焦点
            onFocusIndex: 0,
        };
    }

    componentDidMount() {
        this.numInput.focus();
        this.nowHref = window.location.href;
        window.addEventListener('popstate', this.popstateCallback, false);
    }

    componentWillUnmount() {
        this.interval = null;
        window.removeEventListener('popstate', this.popstateCallback, false);
    }

    popstateCallback = () => {
        this.codeKeyBoard && this.codeKeyBoard.close();
        this.codeKeyBoard = null;
        this.setState({});
    };

    // 电话号码正则校验
    canSubmit() {
        const { telephone, countryCode, pattern } = this.state;
        const reg = new RegExp(pattern);
        return reg.test(`${countryCode}${telephone}`);
    }

    // 发送验证码
    sendCode = () => {
        const { telephone, countryCode } = this.state;
        this.numInput && this.numInput.modal && this.numInput.modal.close();
        if (this.codeKeyBoard) {
            this.codeKeyBoard.close();
            this.codeKeyBoard = null;
        }
        sliderCheck({
            nationCode: countryCode,
            tel: telephone,
            toSendCode: true,
            sendCodeObj: {
                type: 'call',
                callback: () => {
                    WPT.Modal.tips('发送成功');
                    this.codeKeyBoard = 'firstToCodePage';
                    this.setState(
                        {
                            showCodeInputPage: true,
                            seconds: 60,
                            code: ['', '', '', ''],
                            onFocusIndex: 0,
                        },
                        () => {
                            this.countDownStart();
                            this.resetCodeKeyBoard();
                        }
                    );
                },
                failCallback: () => {
                    this.codeKeyBoard = 'firstToCodePage';
                    this.setState(
                        {
                            showCodeInputPage: true,
                            code: ['', '', '', ''],
                            onFocusIndex: 0,
                        },
                        () => {
                            this.countDownStart();
                            this.resetCodeKeyBoard();
                        }
                    );
                },
            },
        });
    };

    // 点击下一步触发
    handleNext = () => {
        if (!this.canSubmit()) return;
        this.sendCode();
    };

    // 选择区号组件的回调函数
    setCountryInfo = (country, countryCode, pattern) => {
        this.setState(
            {
                country,
                countryCode,
                pattern,
            },
            () => {
                this.numInput && this.numInput.focus();
            }
        );
    };

    // 控制显示“选择国家”组件
    setShowCountrycodeList = (value = true) => {
        this.numInput && this.numInput.modal && this.numInput.modal.close();
        this.setState({ showCountryCode: value });
    };

    // 国内手机号格式化 // 从选择区号页面返回时调用
    formatVerifyTelephone = () => {};

    // 渲染登录框
    renderLoginContainer = () => {
        const {
            inputOnFocus, telephone, country, countryCode
        } = this.state;
        const { ccb } = this.props;
        return (
            <div
                className={cx(
                    S.wptWapLogin,
                    inputOnFocus ? S.inputOnFocus : '',
                    this.gobackNoAnimation ? S.noAnimation : ''
                )}
            >
                <div className={S.topBar}>
                    <div className={S.label}>登录</div>
                    <div
                        className={cx(S.close)}
                        onClick={() => {
                            ccb && ccb();
                            this.numInput && this.numInput.modal && this.numInput.modal.close();
                            $('#wptLogin').remove();
                        }}
                    />
                </div>
                <div className={S.inputContainer}>
                    <div className={S.countryCode} onClick={this.setShowCountrycodeList}>
                        {`${country} +${countryCode}`}
                    </div>
                    <div className={S.columnDiliver} />
                    <NumInputView
                        ref={d => {
                            this.numInput = d;
                        }}
                        placeholder="请输入手机号"
                        className={S.numInput}
                        placeholderClass={S.placeHolder}
                        value={telephone}
                        disabled={false}
                        onBlur={() => {
                            this.setState({
                                inputOnFocus: false,
                            });
                        }}
                        onFocus={() => {
                            this.gobackNoAnimation = false;
                            this.setState({
                                inputOnFocus: true,
                            });
                        }}
                        onChange={v => {
                            this.setState({
                                telephone: v,
                            });
                        }}
                        inputNum={{
                            maxLen: 11,
                            dott: false,
                            hideBottomLeft: true,
                            layer: false,
                        }}
                    />
                </div>
                <div className={S.rowDiliver} />
                <div
                    className={cx(S.next, !this.canSubmit() ? S.disabled : '')}
                    onClick={throttle(this.handleNext, 1000)}
                >
                    下一步
                </div>
            </div>
        );
    };

    // 渲染区号选择列表
    renderCountrycodeList = () => (
        <CountryCodeList
            setCountryInfo={this.setCountryInfo}
            setShowCountrycodeList={this.setShowCountrycodeList}
            formatVerifyTelephone={this.formatVerifyTelephone}
            noHistoryBack
        />
    );

    // 验证码重发倒计时开始
    countDownStart = () => {
        const { seconds } = this.state;

        if (!this.interval && seconds !== 0) {
            this.interval = setInterval(() => {
                this.setState(
                    {
                        seconds: this.state.seconds - 1,
                    },
                    () => {
                        if (this.state.seconds === 0) {
                            window.clearInterval(this.interval);
                            this.interval = null;
                        }
                    }
                );
            }, 1000);
        }
    };

    // 输入验证码页面点击返回
    handleLast = () => {
        if (this.codeKeyBoard) {
            this.codeKeyBoard.close();
            this.codeKeyBoard = null;
        }
        this.gobackNoAnimation = true;
        this.setState({
            showCodeInputPage: false,
            code: ['', '', '', ''],
            onFocusIndex: 0,
        });
    };

    // 验证码重发按钮触发
    resendCode = () => {
        if (this.state.seconds !== 0) return;
        this.sendCode();
    };

    renderCodeInputContainer = () => {
        const { code, onFocusIndex } = this.state;
        return (
            <div className={S.codeInputContainer}>
                {code.map((i, index) => (
                    <div
                        className={cx(S.codeContainer, onFocusIndex === index ? S.onfocus : '')}
                        onClick={() => {
                            this.setState({ onFocusIndex: index });
                            this.resetCodeKeyBoard();
                        }}
                    >
                        {i}
                    </div>
                ))}
            </div>
        );
    };

    setCookie(name, value, expiredays) {
        this.exdate = {};
        if (typeof expiredays === 'number') {
            this.exdate = new Date();
            this.exdate.setDate(this.exdate.getDate() + expiredays);
        } else if (typeof expiredays === 'object') {
            this.exdate = expiredays;
        }
        const string = expiredays == null ? '' : `;domain=.weipaitang.com;expires=${this.exdate.toGMTString()};path=/`;
        document.cookie = `${name}=${encodeURIComponent(value)}${string}`;
    }

    // 自动校验验证码后登录
    autoCheckLogin() {
        const { code, telephone, countryCode } = this.state;
        const { scb } = this.props;
        const query = Util.query();
        const param = {
            type: 2,
            telephone,
            nationCode: countryCode,
            verifyCode: code.join(''),
            sc: sessionStorage.getItem('sc'),
            wpjbPromoter: query.wpjbPromoter || '',
        };
        WPT.getData(API.login, param, res => {
            if (res.code === 0 && res.data.cookie) {
                this.setCookie('userinfo_cookie', decodeURIComponent(res.data.cookie), 7);
                scb && scb();
                $('#wptLogin').remove();
            } else {
                WPT.Modal.tips(res.msg);
            }
        });
    }

    // 调起验证码输入框
    resetCodeKeyBoard = () => {
        const href = window.location.href;
        if (this.codeKeyBoard && href === this.nowHref && this.codeKeyBoard !== 'firstToCodePage') return;
        this.nowHref = href;
        this.codeKeyBoard = WPT.Modal.open(
            <InputNum
                ref={c => {
                    this.inputNum = c;
                }}
                hideBottomLeft="true"
                onChange={v => {
                    const hasDeleted = v.length === 0;
                    if (hasDeleted) {
                        const newCodes = [].concat(this.state.code);
                        newCodes[this.state.onFocusIndex] = '';
                        const flag = this.state.onFocusIndex > 0;
                        flag
                            && this.setState({
                                code: [].concat(newCodes),
                                onFocusIndex: this.state.onFocusIndex - 1,
                            });
                        this.state.onFocusIndex === 0
                            && this.setState({
                                code: [].concat(newCodes),
                            });
                    } else {
                        const newCodes = [].concat(this.state.code);
                        newCodes[this.state.onFocusIndex] = v.slice(v.length - 1);
                        const flag = this.state.onFocusIndex < 4;
                        flag
                            && this.setState(
                                {
                                    code: [].concat(newCodes),
                                    onFocusIndex: this.state.onFocusIndex + 1,
                                },
                                () => {
                                    if (
                                        this.state.code.filter(i => i === '').length === 0
                                        && this.state.onFocusIndex === 4
                                    ) {
                                        this.autoCheckLogin();
                                        this.codeKeyBoard.close();
                                        this.codeKeyBoard = null;
                                        this.setState({});
                                    }
                                }
                            );
                    }
                }}
                onDone={() => {
                    this.codeKeyBoard = null;
                    this.setState({
                        onFocusIndex: 4,
                    });
                    if (this.state.code.filter(i => i === '').length === 0) {
                        this.autoCheckLogin();
                    }
                }}
            />,
            {
                animationType: 'dd',
                position: 'bottom',
                layer: false,
            }
        );
    };

    // 渲染验证码输入页面
    renderCodeInputPage = () => {
        const { telephone, seconds } = this.state;
        const { ccb } = this.props;
        return (
            <div className={cx(S.wptCodeCheck, this.codeKeyBoard ? S.inputOnFocus : '')}>
                <div className={S.topBar}>
                    <div className={S.last} onClick={this.handleLast} />
                    <div className={S.label}>请输入验证码</div>
                    <div
                        className={cx(S.close)}
                        onClick={() => {
                            ccb && ccb();
                            this.codeKeyBoard && this.codeKeyBoard.close();
                            this.codeKeyBoard = null;
                            $('#wptLogin').remove();
                        }}
                    />
                </div>
                <div className={S.remindFrom}>请注意接听 0755/0578 等开头的来电</div>
                <div className={S.telephoneContainer}>
                    <div className={S.telephone}>{telephone}</div>
                    <div className={cx(S.countDownButton, seconds === 0 ? '' : S.disabled)} onClick={this.resendCode}>
                        {seconds === 0 ? '重新发送' : `${seconds}秒`}
                    </div>
                </div>
                {this.renderCodeInputContainer()}
            </div>
        );
    };

    render() {
        const { showCountryCode, showCodeInputPage } = this.state;
        return (
            <div className={S.loginMain}>
                {showCountryCode && this.renderCountrycodeList()}
                {!showCountryCode && !showCodeInputPage && this.renderLoginContainer()}
                {showCodeInputPage && this.renderCodeInputPage()}
            </div>
        );
    }
}

/**
 * 弹出登录框
 * @param {function} scb 成功回调
 * @param {function} fcb 失败回调
 * @param {function} ccb 用户关闭窗口回调
 */
function showLogin(scb, fcb, ccb) {
    const wptLoginContainer = document.createElement('div');
    wptLoginContainer.setAttribute('id', 'wptLogin');
    $('body').append(wptLoginContainer);
    ReactDOM.render(<WptWapLogin scb={scb} fcb={fcb} ccb={ccb} />, wptLoginContainer);
}

function loginControl() {
    let options = [];
    let isLoaded = false;

    function login(option, successCallback = () => {}) {
        if (option) {
            options.push(option);
        }
        if (!isLoaded) {
            showLogin(
                () => {
                    WPT.loginRefreshUserinfo(() => {
                        WPT.userinfo.isSubscribe = 1;
                        WPT.loginCallback && WPT.loginCallback();
                        options.forEach(item => {
                            item._repeatAjax ? item._repeatAjax() : $.ajax(item);
                        });
                        options = [];
                        isLoaded = false;
                        loginReport(); // 触发登录上报
                        successCallback();
                    }, options);
                },
                () => {
                    isLoaded = false;
                },
                () => {
                    options = [];
                    isLoaded = false;
                }
            );
            isLoaded = true;
        }
    }
    return login;
}

const login = loginControl();

export { login, showLogin };
